package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

    /**
        用户信息表
    */
@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;
    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 用于查找用户的用户名信息
     *
     * @return
     */
    // http://localhost/user/findUserByUsername.do?username=admin
    @RequestMapping("/getUsername")
    public Result findUserByUsername() {
        // 从 session 中获取
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user != null) {
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, user.getUsername());
        }
        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }

    /**
     * 查询所有的菜单
     * 不同的用户看到的菜单不同
     *
     * @return
     */
    @RequestMapping("/getMenus")
    public Result getMenus() {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        LinkedHashSet<Menu> menus = null;
        LinkedHashSet<Menu> max = new LinkedHashSet<Menu>();
        // 从 redis 中获取对应的 user 对象
        Jedis jedis = jedisPool.getResource();
        String json = jedis.get(user.getUsername());
        com.itheima.pojo.User parse = JSON.parseObject(json, com.itheima.pojo.User.class);
        Set<Role> roles = parse.getRoles();
        // 只有一个角色,
        if (roles.size() == 1) {
            // 遍历
            for (Role role : roles) {
                menus = role.getMenus();
            }
            return new Result(true, null, menus);
        }
        // 不止一个角色
        // 遍历
        for (Role role : roles) {
            menus = role.getMenus();
            if (max.size() <= menus.size()) {
                // 只要从 role对象中获得的菜单集合 比 max 的大,就将大的赋值给max
                max = menus;
            }
        }
        return new Result(true, null, max);
    }
    //添加用户,并可以添加角色给这个用户
    @RequestMapping("/addUser")
    public Result addUser(Integer[] roleIds, @RequestBody com.itheima.pojo.User user) {
        try {
            String password = user.getPassword();
            user.setPassword(passwordEncoder.encode(password));
            userService.addUser(roleIds, user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_ROLE_FAIL);
        }
        return new Result(true, MessageConstant.ADD_ROLE_SUCCESS);

    }
    //根据Id删除用户
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            userService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_ROLE_FAIL);
        }

        return new Result(true, MessageConstant.DELETE_ROLE_SUCCESS);
    }

    /**
     * 查询用户
     * /user/findPage
     * currentPage: this.pagination.currentPage,//页码
     * pageSize: this.pagination.pageSize,//每页显示数
     * queryString: this.pagination.queryString//查询条件
     */
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = userService.pageQuery(queryPageBean);
        return pageResult;
    }

    /**
     * 根据id查询用户信息
     */
    @RequestMapping("findUserById")
    public Result findUserById(Integer id) {
        try {
            com.itheima.pojo.User user = userService.findUserById(id);

            return new Result(true, MessageConstant.QUERY_USER_SUCCESS, user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_USER_FAIL);
        }
    }

    /**
     * 根据用户id查询当前角色ID
     */
    @RequestMapping("findRoleById")
    public Result findRoleById(Integer id) {
        try {
            List<Integer> checkitemIds = userService.findRoleById(id);
            return new Result(true, MessageConstant.QUERY_ROLE_SUCCESS, checkitemIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ROLE_FAIL);
        }
    }
    //编辑用户对应的角色
    @RequestMapping("/editUser")
    public Result editUser(Integer[] roleIds, @RequestBody com.itheima.pojo.User user) {
        try {
            userService.editUser(roleIds, user);
            return new Result(true, MessageConstant.EDIT_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_USER_FAIL);
        }
    }
}
